from rest_framework import serializers
from app01 import models
import re
from rest_framework.exceptions import ValidationError
import hashlib
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from rest_framework_jwt.views import obtain_jwt_token

class LoginSerializer(serializers.ModelSerializer):
    username = serializers.CharField()
    class Meta:
        model = models.UserInfo
        fields = ['username','password','email','mobile']
        extra_kwargs = {
            'password': {'write_only':True},
            'mobile': {
                'error_messages': {
                    'required': '手机号不能为空'
                }
            },
            'email': {
                'error_messages': {
                    'required': '邮箱不能为空'
                }
            },
        }
    def match_user(self,attrs):
        username = attrs.get('username')
        print(username)
        # 匹配手机号
        if re.match(r'^1[3-9][0-9]{9}$', username):
            user_obj = models.UserInfo.objects.filter(mobile=username).first()
        # 匹配邮箱
        elif re.match(r'\w+ @ [a-z0-9] . [a-z]+ /i', username):
            user_obj = models.UserInfo.objects.filter(email=username).first()
        # 匹配账号
        else:
            user_obj = models.UserInfo.objects.filter(username=username).first()
        if not user_obj:
            raise ValidationError('用户名或密码错误')
        password = attrs.get('password').encode('utf-8')
        header = 'oldboy'.encode('utf-8')
        tail = '嘿嘿'.encode('utf-8')
        hash_pwd = hashlib.md5(header + password + tail)
        if not user_obj.password:
            raise ValidationError('校验不通过')
        return user_obj


    def validate(self, attrs):
        user_obj = self.match_user(attrs)
        payload = jwt_payload_handler(user_obj)
        token = jwt_encode_handler(payload)
        # 将token传到视图类中
        self.token = token
        return attrs

